<template>
  <a-drawer
      title="权重设置"
      width="1000"
      placement="right"
      :closable="false"
      :visible="visible"
      :after-visible-change="afterVisibleChange"
      @close="onClose">
    <a-spin :spinning="loading">

      <a-table
          ref="table"
          size="middle"
          bordered
          :rowKey="(record, index) => index"
          :columns="columns"
          :dataSource="dataList"
          :pagination="false">

          <span slot="action" slot-scope="text, record, index">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />

            <a-popconfirm title="确定要删除吗?" @confirm="() => handleDelete(index)">
              <a>删除</a>
            </a-popconfirm>
          </span>

      </a-table>

      <div style="text-align: right">
        <a-button type="link" @click="handleAdd">添加权重</a-button>
      </div>

      <div v-if="formVisible" style="padding: 10px 20px; background-color: rgba(243, 243, 243, 1)">
        <div>添加/编辑</div>
        <a-form-model layout="inline" :model="form">
          <a-row :gutter="24">
            <!--            <a-col :md="6" :sm="8" v-for="item in columns" :key="item.dataIndex" v-if="item.dataIndex !== 'action'">-->
            <!--              <a-form-model-item :label="item.title" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
            <!--                <a-input-number v-model="form[item.dataIndex]" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重1" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level1" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重2" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level2" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重3" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level3" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重4" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level4" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重5" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level5" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重6" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level6" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重7" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level7" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-model-item label="权重8" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="form.level8" :min="0" :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="anty-form-btn" style="text-align: right; position: relative">
          <div style="position: absolute; bottom: 0; color: crimson">权重之和必须为100%</div>
          <a-button @click="closeForm" type="default" htmlType="button" icon="close">取消</a-button>
          <a-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</a-button>
        </div>
      </div>
    </a-spin>

    <div :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'center',
          zIndex: 1,
        }">
      <a-button :style="{ marginRight: '8px' }" @click="onClose">
        关闭
      </a-button>
      <a-button type="primary" @click="onClose">
        确定
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import {deleteAction, getAction, httpAction, postdeleteAction} from '@/api/manage'

export default {
  name: "title-form",
  data () {
    return {
      visible: false,
      formVisible: false,
      dataForm: {
        questionId: '',
      },
      form: {
        level1: '0',
        level2: '0',
        level3: '0',
        level4: '0',
        level5: '0',
        level6: '0',
        level7: '0',
        level8: '0',
      },
      loading: false,
      dataList: [
        {
          id: '',
          level1: '10',
          level2: '10',
          level3: '10',
          level4: '15',
          level5: '15',
          level6: '15',
          level7: '15',
          level8: '10',
        },
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      columns: [
        {
          title: '权重1',
          dataIndex: 'level1',
        },
        {
          title: '权重2',
          dataIndex: 'level2',
        },
        {
          title: '权重3',
          dataIndex: 'level3',
        },
        {
          title: '权重4',
          dataIndex: 'level4',
        },
        {
          title: '权重5',
          dataIndex: 'level5',
        },
        {
          title: '权重6',
          dataIndex: 'level6',
        },
        {
          title: '权重7',
          dataIndex: 'level7',
        },
        {
          title: '权重8',
          dataIndex: 'level8',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: "center",
          width: 170,
        }
      ],
      url: {
        getList: '/weight/getList',
        getInfo: '/weight/getInfo',
        save: '/weight/saveWeight',
        edit: '/weight/editWeight',
        delete: '/weight/delWeight',
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      if (this.dataForm.questionId) {
        this.loading = true
        Promise.all([
          // this.getColumns(),
          this.getInfo()
        ]).then(() => {
          this.loading = false
        }).catch(() => {
          this.visible = false
          this.loading = false
        })
      }
    },
    getColumns () {
      return new Promise((resolve, reject) => {
        getAction(this.url.getList).then(res => {
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.columns = []
          res.result.forEach(res => {
            this.columns.push({ title: res.appraiseTies, dataIndex: res.appraiseTiesId, align: "center" })
            this.form[res.dataIndex] = '0'
          })
          this.columns.push({
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: "center",
            width: 170
          })
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    getInfo () {
      return new Promise((resolve, reject) => {
        getAction(this.url.getInfo, this.dataForm).then(res => {
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.dataList = res.result
          // this.dataList = []
          // res.result.forEach(res => {
          //   let data = {}
          //   res.dataList.forEach(item => {
          //     data[item.appraiseTiesId] = item.valued
          //     data.dataId = res.dataId
          //   })
          //   this.dataList.push(data)
          // })
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    submitCurrForm () {
      let dataId = this.form.id
      let dataList = Object.assign({}, this.form)
      delete dataList.id
      delete dataList.questionId
      let weightSum = Object.values(dataList).reduce((prev, curr) => prev + curr)
      console.log('weightSum', weightSum)
      if (100 !== weightSum) {
        return this.$message.error('权重之和必须为100%')
      }

      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].id === dataId) {
          continue;
        }
        let b = true;
        for (let [key, value] of Object.entries(this.form)) {
          if (value !== 0) {
            if (this.dataList[i][key] === 0) {
              b = false
              break;
            }
          } else {
            if (this.dataList[i][key] !== 0) {
              b = false
              break;
            }
          }
        }
        if (b) {
          return this.$message.warn('已添加同种类型的权重！')
        }
      }
      // for (let i = 0; i < this.dataList.length; i++) {
      //   if (this.form.directSuperior !== 0) {
      //     if (this.dataList[i].directSuperior === 0) {
      //       b = false;
      //       break;
      //     }
      //   } else {
      //     if (this.dataList[i].directSuperior !== 0) {
      //       b = false;
      //       break;
      //     }
      //   }
      //   if (this.form.relevantSuperiors !== 0) {
      //     if (this.dataList[i].relevantSuperiors === 0) {
      //       b = false;
      //       break;
      //     }
      //   } else {
      //     if (this.dataList[i].relevantSuperiors !== 0) {
      //       b = false;
      //       break;
      //     }
      //   }
      //   if (this.form.directSibling !== 0) {
      //     if (this.dataList[i].directSibling === 0) {
      //       b = false;
      //       break;
      //     }
      //   } else {
      //     if (this.dataList[i].directSibling !== 0) {
      //       b = false;
      //       break;
      //     }
      //   }
      //   if (this.form.relevantSibling !== 0) {
      //     if (this.dataList[i].relevantSibling === 0) {
      //       b = false;
      //       break;
      //     }
      //   } else {
      //     if (this.dataList[i].relevantSibling !== 0) {
      //       b = false;
      //       break;
      //     }
      //   }
      //   if (this.form.subordinate !== 0) {
      //     if (this.dataList[i].subordinate === 0) {
      //       b = false;
      //       break;
      //     }
      //   } else {
      //     if (this.dataList[i].subordinate !== 0) {
      //       b = false;
      //       break;
      //     }
      //   }
      // }
      this.loading = true
      let method
      let url
      if (dataId) {
        method = 'post'
        url = this.url.edit
      } else {
        method = 'post'
        url = this.url.save
      }
      let form = Object.assign({ id: dataId, questionId: this.dataForm.questionId }, this.form)
      httpAction(url, form, method).then((res) => {
        if (res.success) {
          this.$message.success({
            content: '保存成功!',
            duration: 1,
            onClose: () => {
              this.getInfo()
              this.loading = false
              this.formVisible = false
            }
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    afterVisibleChange () {
    },
    onClose () {
      this.visible = false
      this.formVisible = false
    },
    closeForm () {
      this.formVisible = false
    },
    handleEdit (record) {
      this.formVisible = true
      console.log('record', record)
      this.form = record
    },
    handleDelete (index) {
      if (this.dataList[index].id) {
        postdeleteAction(this.url.delete, { idList: [this.dataList[index].id] }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.formVisible = false
            this.dataList.splice(index, 1)
          } else {
            this.$message.warning(res.message);
          }
        })
      } else {
        this.formVisible = false
        this.dataList.splice(index, 1)
      }
    },
    handleAdd () {
      const newData = {}
      for (let i = 0; i < this.columns.length - 1; i++) {
        newData[this.columns[i].dataIndex] = 0
      }
      // newData.questionId = this.dataForm.questionId
      this.formVisible = true
      this.form = newData
      this.dataList.push(newData)
    }
  }
}
</script>

<style scoped>

</style>
